package com.seeTools.next.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口请求耗时拦截器
 *
 * @author xiaotong
 */
@Slf4j
@Component
public class RequestTimeInterceptor implements HandlerInterceptor {

    private static final String START_TIME = "requestStartTime";

    private static final long SLOW_TIME = 1000;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute(START_TIME, startTime);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long startTime = (Long) request.getAttribute(START_TIME);
        long endTime = System.currentTimeMillis();
        long executeTime = endTime - startTime;
        if (executeTime > SLOW_TIME) {
            log.warn("[{}] {} {} {}ms", request.getMethod(), request.getRequestURI(), response.getStatus(), executeTime);
        } else {
            log.info("[{}] {} {} {}ms", request.getMethod(), request.getRequestURI(), response.getStatus(), executeTime);
        }
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
